package com.jcsz.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.jcsz.common.to.mq.OrderTo;
import com.jcsz.common.to.mq.StockDetailTo;
import com.jcsz.common.to.mq.StockLockedTo;
import com.jcsz.common.utils.R;
import com.jcsz.gulimall.ware.entity.WareOrderTaskEntity;
import com.jcsz.gulimall.ware.feign.OrderFeignService;
import com.jcsz.gulimall.ware.service.WareOrderTaskService;
import com.jcsz.gulimall.ware.service.WareSkuService;
import com.jcsz.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @className: StockReleaseListener
 * @author: 一把Po吉他
 * @date: 2022/11/16 10:23
 * @version: 1.0
 **/
@RabbitListener(queues = "stock.release.stock.queue")
@Component
@Slf4j
public class StockReleaseListener {
    @Autowired
    private OrderFeignService orderFeignService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     * <p>
     * 2、订单失败
     * 库存锁定失败
     * <p>
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败
     */
    @RabbitHandler
    public void handleStockLockedRelease(Message message, StockLockedTo stockLockedTo, Channel channel) throws IOException {
        log.info("******收到解锁库存的信息******");
        try {
            wareSkuService.unLockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
    @RabbitHandler
    public void handleStockLockedRelease(Message message, OrderTo orderTo, Channel channel) throws IOException {
        log.info("******收到解锁库存的信息--订单关闭******");
        try {
            wareSkuService.unLockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

}
